package com.young.controller;

import com.young.entity.Topic;
import com.young.entity.User;
import com.young.service.TopicService;
import com.young.service.UserService;
import com.young.util.ResultVOUtil;
import com.young.vo.ResultVO;
import com.young.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class DemoController {
    @Autowired
    private UserService userService;
    @Autowired
    private TopicService topicService;
    @PostMapping("/login")
    public ResultVO login(@RequestBody UserVO userVO, HttpServletRequest request){
        User user = userService.login(userVO.getUsername(), userVO.getPassword());
        if (user==null){
            return ResultVOUtil.fail(400,"用户名或密码错误");
        }
        request.getSession().setAttribute("user",user);
        return ResultVOUtil.success(user);
    }
    @PostMapping("/topic")
    public ResultVO addTopic(@RequestBody Topic topic,HttpServletRequest request){
        User user = (User)request.getSession().getAttribute("user");
        if (user==null){
            return ResultVOUtil.fail(400,"用户未登录");
        }
        topic.setUserId(user.getId());
        if (topicService.saveTopic(topic)){
            return ResultVOUtil.success();
        }
        return ResultVOUtil.fail(400,"发布话题失败");
    }
}
